const { app, resolvepath, logger } = require("../setting/setting.js");
const { dbobject } = require("../database/database.js");
const setting = require("../token/setting");
const verify = require("../token/verify");
const { myfs } = require("../myfs/myfs");

//获取token
app.post("/api/gettoken", (req, res) => {
  verify.setToken("123456").then(async (token) => {
    res.status(200);
    res.json({
      token,
      signTime: setting.token.signTime,
    });
  });
});

app.get("/home", async(req, res) => {
  const result = await myfs.readflie("/visitsnumber/visitsnumber.txt");
  if(result){
    res.status(200);
    res.send(result.toString());
  }
  else{
    res.status(500);
  }
});

//获取留言板信息
app.get("/messageboard", (req, res) => {
  try {
    dbobject.db.query("SELECT * FROM barrage", (error, results) => {
      if (error) {
        logger.publicerror("Mysql Select", error.message);
        res.status(500);
        res.send("SELECT ERROR");
      } else {
        res.status(200);
        res.send({
          messageboard: results,
        });
      }
    });
  } catch (error) {
    throw error;
  }
});

//提交留言板
app.post("/messageboard/form", (req, res) => {
  const emailpatt = /\b[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,6}\b/g;

  let query = {
    username: req.body.name.length > 1 ? req.body.name : res.send("参数错误"),
    email: emailpatt.test(req.body.email)
      ? req.body.email
      : res.send("参数错误"),
    content:
      req.body.content.length > 1 ? req.body.content : res.send("参数错误"),
    time: req.body.time.length > 1 ? req.body.time : res.send("参数错误"),
    speed: req.body.speed.length > 1 ? req.body.speed : res.send("参数错误"),
  };
  let sql = "INSERT INTO barrage SET ?";

  try {
    dbobject.db.query(sql, query, (error, results) => {
      if (error) {
        logger.publicerror("Mysql Insert", error.message);
        res.status(500);
        res.send(error.message);
      } else {
        res.status(200);
        res.send("提交成功 感谢您的留言");
      }
    });
  } catch (error) {
    throw error;
  }
});

//获取侧边导航栏及其参数
app.get("/getflienav", (req, res) => {
  async function read() {
    const path = req.query.path;
    let result = {};
    let count = 0;

    const firstDirectory = await myfs.readdir(path);

    for (let i in firstDirectory) {
      let fullpath = path + "/" + firstDirectory[i];
      let secondDirectory = await myfs.readdir(fullpath);
      result[`item${count}`] = {
        text: firstDirectory[i],
        item: {},
      };
      for (let j in secondDirectory) {
        result[`item${count}`].item[secondDirectory[j]] = {
          text: secondDirectory[j].replace(/.md/g, ""),
          path: `${fullpath}/${secondDirectory[j]}`,
          query: secondDirectory[j].replace(/.md/g, ""),
        };
      }
      count++;
    }

    let keyArr = Object.keys(result);

    for (let i = 0; i < keyArr.length; i++) {
      for (let j = 0; j < keyArr.length - i - 1; j++) {
        let resultArr1 = Object.keys(result[keyArr[j]].item);
        let resultArr2 = Object.keys(result[keyArr[j + 1]].item);

        if (resultArr1.length < resultArr2.length) {
          let temp = result[keyArr[j]];
          result[keyArr[j]] = result[keyArr[j + 1]];
          result[keyArr[j + 1]] = temp;
        }
      }
    }

    return result;
  }

  async function begin() {
    let result = await read();
    res.status(200);
    res.send(result);
  }

  begin();
});

//获取点赞数
app.get("/getthumbsup", (req, res) => {
  try {
    dbobject.db.query(
      `SELECT thumbsupnumber FROM articleinfo WHERE query='${req.query.query}'`,
      (error, results) => {
        if (error) {
          logger.publicerror("Mysql Select", error.message);
          res.status(500);
          res.send("SELECT ERROR");
        } else {
          res.status(200);
          res.send(results);
        }
      }
    );
  } catch (error) {
    throw error;
  }
});

//提交点赞
app.post("/thumbsup", (req, res) => {
  const query = req.body.query;

  try {
    dbobject.db.query(
      `update articleinfo set thumbsupnumber=thumbsupnumber+1 where query = '${query}'`,
      (error, results) => {
        if (error) {
          logger.publicerror("Mysql Select", error.message);
          res.status(500);
          res.send("SELECT ERROR");
        } else {
          logger.publicinfo(`有用户点赞了,点赞文章为`, query);
          res.status(200);
          res.send("感谢点赞");
        }
      }
    );
  } catch (error) {
    throw error;
  }
});

//获取文章内容
app.get("/getarticleinfo", (req, res) => {
  const query =
    req.query.query ||
    "L2ZsaWUvVnVlL1Z1ZeWwgeijheS4gOS4quWKqOaAgei%2m+WFpeaViOaenOeahOe7hOS7ti5tZA==";

  try {
    dbobject.db.query(
      `update articleinfo set readingnumber=readingnumber+1 where query = '${query}'`,
      (error, results) => {
        if (error) {
          logger.publicerror("Mysql Select", error.message);
        } else {
          logger.publicinfo(`有用户浏览文章了,浏览文章为`, query);
        }
      }
    );
    dbobject.db.query(
      `SELECT path FROM articleinfo where query = '${query}'`,
      async (error, results) => {
        if (error) {
          logger.publicerror("Mysql Select", error.message);
          res.status(500);
          res.send("SELECT ERROR");
        } else {
          const result = await myfs.readflie(results[0].path);
          res.status(200);
          res.send(result);
        }
      }
    );
  } catch (error) {
    throw error;
  }
});

//获取高达墙信息
app.get("/gundamwall", (req, res) => {
  try {
    dbobject.db.query("SELECT * FROM gundamwall", (error, results) => {
      if (error) {
        logger.publicerror("Mysql Select", error.message);
        res.status(500);
        res.send("SELECT ERROR");
      } else {
        res.status(200);
        res.send(results);
      }
    });
  } catch (error) {
    throw error;
  }
});

//搜索功能
app.get('/search',(req,res)=>{
  const query=req.query.query;
  const dataArr=dbobject.db.query("SELECT * FROM articleinfo")
})

app.get("/api/info", async (req, res) => {
  let data = await verify.getToken(req.query.token);
  // 有些请求是需要登录状态的 所以验证token
  // 验证 data.state >>> true Or false
  data.state
    ? res.json({
        status: 0,
        msg: "可以访问",
      })
    : res.json({
        status: -1,
        msg: "请登录",
      });
});

module.exports = {
  app,
};
